/**
 * 临时登录
 */

import { message } from "antd";
import { postSyhtSysLogin } from "../../api/login";
import { useNavigate } from "react-router-dom";
import { getAllDictionaryEntries } from "../../assets/fun/DictionaryItem";
import { CardBox, LoginBox } from "./style";
import { basicIp } from "../../api/http";
import { useState } from "react";

interface LoginCallbackData {
  token: string; // 登录成功后返回的token
}

const randomIntegerFun = () => {
  return Math.floor(Math.random() * 1000);
}

const Login = () => {
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const [suijiNum, setSuijiNum] = useState(randomIntegerFun()); // 验证码流水号
  const [userName, setUserName] = useState<string>(); //登录账号
  const [password, setPassword] = useState<string>(); //登录密码
  const [codeValue, setCodeValue] = useState<string>(); //验证码
  

  //点击刷新
  const handleImageRenovate = () => {
    setSuijiNum(randomIntegerFun());
  };

  // 登录
  const handleLogin = async () => {
    if (!userName) {
      messageApi.warning("请输入账号！");
    } else if (!password) {
      messageApi.warning("请输入密码！");
    } else if (!codeValue) {
      messageApi.warning("请输入验证码！");
    } else {
      const parames = {
        captcha: codeValue,
        userName, //登录账号
        password, //登录密码
        random: suijiNum,
      };
      const { code, msg, data } = (await postSyhtSysLogin(parames)) as {
        code: number;
        msg: string;
        data: LoginCallbackData;
      };
      if (code === 200) {
        sessionStorage.setItem('token', data.token);
        sessionStorage.setItem('login', JSON.stringify(data));
        // sessionStorage.setItem('menu', '/home/config/menuPage/menuPage');
        getAllDictionaryEntries(); //获取所有字典项
        navigate('/itemManagement');
      } else {
        messageApi.error(msg);
      }
    }
  };

  return <LoginBox>
    <CardBox>
      <div className="title">
        欢迎登录
      </div>
      <div className="input_title">账号</div>
      <input placeholder="请输入账号" value={userName} onChange={e => setUserName(e.target.value)} className="login_input" />
      <div className="input_title">密码</div>
      <input type='password' placeholder="请输入密码" value={password} onChange={e => setPassword(e.target.value)} className="login_input" />
      <div className="input_title">图形验证码</div>
      <div className="code_type">
        <input placeholder="请输入验证码" value={codeValue} onChange={e => setCodeValue(e.target.value)} className="login_input yanzhengma" />
        <img
          alt="验证码"
          className="image_style"
          title="点击刷新"
          src={`${basicIp}/syht/sys/getCaptcha/${suijiNum}`}
          onClick={handleImageRenovate}
        />
      </div>
      <div className="submit_box" onClick={() => handleLogin()}>
        登录
      </div>
    </CardBox>
    {contextHolder}
  </LoginBox>
}

export default Login;